package com.ouroboroswiki.web.operation;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentValidationException;
import com.ouroboroswiki.core.WritableContentRepository;
import com.ouroboroswiki.web.ContentOperation;

public class SaveContentOperation extends ContentOperationSupport implements ContentOperation {
	
	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(SaveContentOperation.class.getName());
	
	public static final String PARAMETER_PATH = "path";
	public static final String PARAMETER_REPOSITORY = "repo";
	public static final String PARAMETER_CONTENT = "content";
	
	private String result;
	private Map<String, WritableContentRepository> repositories;
	
	public SaveContentOperation( Collection<WritableContentRepository> repositories, String result ) {
		this.repositories = new HashMap<String, WritableContentRepository>( repositories.size() );
		for( WritableContentRepository repository : repositories ) {
			this.repositories.put( repository.getName(), repository);
		}
		this.result = result;
	}

	@Override
	@SuppressWarnings("rawtypes")
	public String perform(Object[] principal, ContentPath uniqueId, Map parameters) throws ContentException, ContentValidationException, IOException {
		String path = getParameter(PARAMETER_PATH, parameters);
		String repo = getParameter(PARAMETER_REPOSITORY, parameters);
		String content = getParameter(PARAMETER_CONTENT, parameters);
		WritableContentRepository repository = repositories.get( repo );
		ByteArrayInputStream ins = new ByteArrayInputStream( content.getBytes() );
		repository.writeToContent(principal[0], path, ins );
		return result;
	}
	
}
